#include "editteam.h"
#include "ui_editteam.h"
#include <QtSql/QSqlDatabase>
#include <QtSql/QSqlError>
#include <QtSql/QSqlQuery>
#include <QVariant>
#include <QDebug>



EditTeam::EditTeam(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::EditTeam)
{
    ui->setupUi(this);
    dbconnection = DbConnect();
    getTeams();
    populateComboBox();
    pupulatePlayers();
    showPlayers();
}

EditTeam::~EditTeam()
{
    delete ui;
}

void EditTeam::getTeams() {

   QSqlQuery query("Select * from teams");

   while(query.next()) {
       Team *temp_team = new Team();
       temp_team->setName(query.value(0).toString());
       temp_team->setId(query.value(1).toInt());
       all_teams.append(temp_team);
  }
   query.finish();

}

void EditTeam::populateComboBox() {

   foreach(Team *each_team, all_teams) {
       ui->comboBox->addItem(each_team->getName(), QVariant(each_team->getID()));
         }

}

void EditTeam::pupulatePlayers() {


    QSqlQuery query("Select * from players");

     while(query.next()) {
         PlayerRadio *radiobutton = new PlayerRadio(this);
         QString text = QString("%1 %2 - %3").arg(query.value(0).toString()).arg(query.value(2).toString()).arg(query.value(3).toString());
         radiobutton->setText(text);
         radiobutton->setU_id(query.value(4).toInt());
         all_players.append(radiobutton);
         ui->verticalLayout->addWidget(radiobutton);
    }

    query.finish();
}

void EditTeam::showPlayers() {   // This is horrible algorithm.  Needs to be fixed.

    qDebug() << ui->comboBox->currentIndex();
    Team* selectedTeam;
    int current_team_id = ui->comboBox->itemData(ui->comboBox->currentIndex()).toInt();
    foreach(Team *each_team, all_teams){
        if(each_team->getID() == current_team_id)
            selectedTeam = each_team;
        qDebug() << "Selected team: " << selectedTeam->getID();
    }

    selectedTeam->getRoster();
    //selectedTeam->debugRoster();


    foreach(PlayerRadio *pr, all_players) {
        if(selectedTeam->hasPlayer(pr->getU_id())) {
            pr->setChecked(true); }
        else pr->setChecked(false);
    }
}

void EditTeam::saveTeam() {

    Team* selectedTeam;
    int current_team_id = ui->comboBox->itemData(ui->comboBox->currentIndex()).toInt();
    foreach(Team *each_team, all_teams){
        if(each_team->getID() == current_team_id)
            selectedTeam = each_team;

    }



    QList<int> add;
    QList<int> remove;


    foreach(PlayerRadio* pl, all_players) {
        if (pl->isChecked() == true) {
            if(!selectedTeam->hasPlayer(pl->getU_id())) {
                add.append(pl->getU_id());
            }
        } if (pl->isChecked() == false) {
            if(selectedTeam->hasPlayer(pl->getU_id())) {
                remove.append(pl->getU_id());
            }
        }
    }

    selectedTeam->updateRoster(add,remove);
    this->close();

}

void EditTeam::goBack() {
    this->close();
}





